package com.craftplay.configuration;

import com.craftplay.dao.PayRedPackageMapper;
import com.craftplay.model.PayRedPackage;
import com.craftplay.model.User;
import com.craftplay.service.UserService;
import com.github.binarywang.wxpay.bean.entpay.EntPayRequest;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 微信零钱发送任务
 * @Author: JL
 * @CreateDate: 2019/9/10 16:41
 * @Version: 1.0
 */
@Component
@Configuration
@EnableScheduling
public class WxPayChangeTask {

    @Autowired
    private WxPayService wxService;

    @Autowired
    UserService userService;

    @Autowired
    private PayRedPackageMapper payRedPackageMapper;


//    @Scheduled(cron = "0 0 0 */1 * ?")
    private void configureTasks() {
        System.out.println("微信零钱发送任务执行: "+new Date());
        Date nowTime = new Date();
        List<PayRedPackage> payRedPackages = payRedPackageMapper.selectByStatus(2);
        Map<Integer, List<PayRedPackage>> collect = payRedPackages.stream().collect(Collectors.groupingBy(t -> t.getUserid()));
        collect.forEach((userId, redPackages) -> {
            int money = 0;
            for (PayRedPackage redPackage : redPackages) {
                money += redPackage.getMoney();
            }
            //获取发送的用户
            User user = userService.selectUserById(userId);
            if (money > 0) {
                EntPayRequest request = new EntPayRequest();
                String redOutReadeNo = "JWRP" + (nowTime.getTime()) + userId;
                request.setPartnerTradeNo(redOutReadeNo);
                request.setOpenid(user.getOpenId());
                request.setCheckName("NO_CHECK");
                request.setAmount(money);
                request.setDescription("有人解锁了你的匠玩");
                request.setSpbillCreateIp("192.168.20.202");
                try {
                    wxService.getEntPayService().entPay(request);
                    //发送成置位发送成功红包
                    for (PayRedPackage redPackage : redPackages) {
                        redPackage.setStatus(3);//发送到余额
                        redPackage.setPaytime(new Date());
                        payRedPackageMapper.updateByPrimaryKey(redPackage);
                    }
                    System.out.println("发送余额到: " + userId + "一共价值" + money);
                } catch (WxPayException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
